package cn.com.ddapp.ddm.widget.pulltorefresh.pullableview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;

/**
 * 能够兼容ViewPager的PullableListView
 * 
 * @Description: 解决了ViewPager在listView中的滑动反弹问题
 * 
 * @File: PullableListViewExtend.java
 * 
 * @Author gw
 * 
 * @Date 2015-10-18 下午02:34:50
 * 
 * @Version V1.0
 */
public class PullableNoDownListViewExtend extends ListView implements Pullable {
	// 滑动距离及坐标
	private float xDistance, yDistance, xLast, yLast;

	public PullableNoDownListViewExtend(Context context) {
		super(context);
	}

	public PullableNoDownListViewExtend(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PullableNoDownListViewExtend(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public boolean canPullDown() {
		if (getCount() == 0) {
			// 没有item的时候也可以下拉刷新
			return true;
		} else if (getFirstVisiblePosition() == 0
				&& getChildAt(0).getTop() >= 0) {
			// 滑到ListView的顶部了
			return true;
		} else
			return false;
	}

	@Override
	public boolean canPullUp() {
//		if (getCount() == 0) {
//			// 没有item的时候也可以上拉加载
//			return true;
//		} else if (getLastVisiblePosition() == (getCount() - 1)) {
//			// 滑到底部了
//			if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
//					&& getChildAt(
//							getLastVisiblePosition()
//									- getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
//				return true;
//		}
		return false;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			xDistance = yDistance = 0f;
			xLast = ev.getX();
			yLast = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			final float curX = ev.getX();
			final float curY = ev.getY();

			xDistance += Math.abs(curX - xLast);
			yDistance += Math.abs(curY - yLast);
			xLast = curX;
			yLast = curY;

			if (xDistance > yDistance) {
				return false;
			}
		}

		return super.onInterceptTouchEvent(ev);
	}
}
